<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Document</title>
<style>
  .router-link-active{
    background-color: red;
  }
</style>
</head>
<body>

  <div id='app'>

    <router-link tag="button" to="/home">首页</router-link>
    <router-link tag="button" to="/news">新闻页</router-link>
    <router-link tag="button" to="/about">关于</router-link>
    <hr>
    <!-- 路由组件的出口 -->
    <router-view />
  </div>

<script src='https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js'></script>
<script src="./vue-router.js"></script>
<script>
  const Home = {
    template: `
      <div>
        home页
      </div>
    `
  }
  const About = {
    template: `
      <div>
        关于我们
      </div>
    `
  }
  const News = {
    template: `
      <div>
        新闻页
      </div>
    `,
    mounted() {
      console.log(this);
    }
  }
  const Login = {
    template: `
      <div>
        登录页
        <button @click="login">登录</button>
      </div>
    `,
    methods:{
      login(){
        setTimeout(() => {
          const token = "ascaqaiuhciobah213213";
          localStorage.setItem('access_token', token)
          if(this.$route.params.from){
            // 说明没有登录 重定向过来的
            this.$router.push(this.$route.params.from)
          }else{
            this.$router.push('/home')
          }
        }, 1000)
      }
    },
    mounted() {
      console.log(this);
    }
  }
  // 定义路由
  const routes = [   // 配置路由规则
    {
      path: '/',
      component: Home
    },
    {
      path: '/home',
      component: Home
    },
    {
      path: '/news',
      component: News
    },
    {
      path: '/about',
      component: About
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    }
  ]
  const router = new VueRouter({  // 注册路由
    routes
  })
  // 前置守卫
  router.beforeEach((to, from, next) => {
    // 先判断是否去登录或注册页 这俩直接放行
    // 判断用户是否登录，登录 next方法， 未定义 重定向到登录页
    if(to.fullPath === '/login' || to.fullPath === '/register'){
      next();
    }else{
      const token = localStorage.getItem('access_token');
      if(token){
        next();
      }else{
        next({
          name: 'login',
          params: {
            from: to.fullPath
          }
        });
      }
    }
  })
  const app = new Vue({
    el: '#app'
    ,router   // 挂载实例
  })

</script>
</body>
</html>